package cn.kgc.springmvc.day03.controller;

import cn.hutool.json.JSONUtil;
import cn.kgc.springmvc.day03.respose.ResponseResult;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 课工场
 * @date 2024/11/12
 * @description  控制层响应数据格式
 *
 * @ResponseBody  声明的返回的数据格式为json
 *   使用位置
 *      1. method   只对当前方法有效
 *      2. type  类上   类中所有的方法返回值均已json格式返回
 *
 * @Controller  +    @ResponseBody  =  @RestController  组合注解
 *
 * @RestController
 *      1.声明了对象的托管 spring
 *      2. 声明当前类所有的方法返回值为json格式
 *
 */

@Controller
@RequestMapping("resp")
// @RestController
public class ResponseController {


    /*
    *   ModelAndView    view  -> 转发        model  -> request
    *
    * */
    @RequestMapping("m1")
    public ModelAndView method1(){

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("info","response");
        modelAndView.setViewName("main");
        return modelAndView;
    }

/*
*   String    字符串表示需要跳转的视图名
*    转发    视图解析器     /main.jsp
*
* */
    @RequestMapping("m2")
    public String method2(Model model){
        model.addAttribute("info","model");
        return "main";
    }


    // json
    @RequestMapping("m3")
    @ResponseBody   //  声明返回的数据格式为json   java  ResponseResult  -> json  String
    public ResponseResult method3(){

        //  调用业务层  处理业务 得到返回结果   responseResult
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(0);
        responseResult.setMsg("hello");
        responseResult.setCount(100L);


        return  responseResult;
    }

    @RequestMapping("m4")
    @ResponseBody   //  声明返回的数据格式为json   java  ResponseResult  -> json  String
    public Map<String,Object> method4(){
        //  调用业务层  处理业务 得到返回结果   responseResult
        HashMap<String, Object> result = new HashMap<>();
        result.put("code",0);
        result.put("msg","hello");
        result.put("count",100);

        return result;
    }


    @RequestMapping("m5")
    public void method5(HttpServletRequest request, HttpServletResponse response){

        HashMap<String, Object> result = new HashMap<>();
        result.put("code",110);
        result.put("msg","hello");
        result.put("count",500);

        response.setContentType("application/json;charset=utf-8");
        try {
            PrintWriter writer = response.getWriter();
            String jsonStr = JSONUtil.toJsonStr(result);
            writer.write(jsonStr);
            writer.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
